package org.entor.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.entor.entity.User;

import com.entor.dbutil.Databaseutil;
import com.entor.sql.UserDaoImpl;

public class HandleCookie {

//	根据cookie判断用户是否登录，如果登录返回true
	public static String loginState(HttpServletRequest req){
		Cookie[] cookies = req.getCookies();
		/*
		 * 之前没有设置cookie的path，所以在这里只能获取到sessionid，在设置了path之后，获取到了所有的cookie
		 */
		String uname = "";
		int uid = 0;
//		System.out.println(cookies.length);
		if(cookies==null){
			return "";
		}
		if(cookies.length>1){
//			System.out.println("wuc");
			for(Cookie cookie:cookies){
//				System.out.println(cookie.getName()+"\t"+cookie.getValue());
//				判断字符串相等应使用equals，而不是==
				if(cookie.getName().equals("uname")){
//					System.out.println("uname="+uname);
					uname = cookie.getValue();
//					System.out.println(uname);
				}else if(cookie.getName().equals("uid")){
//					System.out.println("uid="+uid);
					uid = Databaseutil.stringtoint(cookie.getValue());
//					System.out.println(uid);
				}
			}
			User user = new User();
			user.setUid(uid);
			user.setUname(uname);
			UserDaoImpl udi = new UserDaoImpl();
			if(udi.verificationUserBycookie(user)){
//				System.out.println(uname+"54163");
				return uname;
			}
		}
//		System.out.println("cookie不对");
		return "";
	}
}
